package com.qcb.expresswrapping.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qcb.expresswrapping.common.Const;
import com.qcb.expresswrapping.exception.CaptchaException;
import com.qcb.expresswrapping.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: QCB
 * @create: 2021-12-30-21:18
 * To change this template use File | Settings | File and Code Templates.
 */
@Component
@Slf4j
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String url = httpServletRequest.getRequestURI();
        if ("/login".equals(url) && httpServletRequest.getMethod().equals("POST")){
            log.info("获取到login链接，正在校验验证码 -- " + url);
            try {
                // 校验验证码
                validate(httpServletRequest);
            } catch (CaptchaException e){
                // 交给认证失败处理器处理
                loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            }
        }

        // 校验通过，放行
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private void validate(HttpServletRequest httpServletRequest) {
        String code = httpServletRequest.getParameter("code");
        String key = httpServletRequest.getParameter("keyCode");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(key)){
            throw new CaptchaException("验证码不能为空");
        }

        if (!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))){
            throw new CaptchaException("验证码错误");
        }

        // 验证码用完之后就删掉
        redisUtil.hdel(Const.CAPTCHA_KEY, key);
    }
}
